
var BOSH_SERVICE = '/http-bind/';
var connection = null;

function log(msg)
{
    console.log(document.createTextNode(msg));
}

function rawInput(data)
{
    log('RECV: ' + data);
}

function rawOutput(data)
{
    log('SENT: ' + data);
}

function onConnect(status)
{
    if (status == Strophe.Status.CONNECTING) {
	log('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
	log('Strophe failed to connect.');
	$('#connexion').get(0).innerHTML = 'connect';
    } else if (status == Strophe.Status.DISCONNECTING) {
	log('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
	log('Strophe is disconnected.');
	$('#connexion').get(0).innerHTML = 'connect';
    } else if (status == Strophe.Status.CONNECTED) {
	log('Strophe is connected.');

    log('ECHOBOT: Send a message to ' + connection.jid +
	    ' to talk to me.');

	connection.addHandler(onMessage, null, 'message', null, null,  null);
	connection.send($pres().tree());

    }
}

function onMessage(msg) {
    var to = msg.getAttribute('to');
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

    if (type == "chat" && elems.length > 0) {
	var body = elems[0];

	log('ECHOBOT: I got a message from ' + from + ': ' +
	    Strophe.getText(body));
//datejs

  var d = new Date();
    $('#messages').append('<article><header class="message"><p><i>('
        + new Date().toString("HH:mm.ss")
        + ')</i><b> '
        + Strophe.getNodeFromJid(from)
        + '</b> said :</p></header><p>'
        + Strophe.getText(body)
        +'</p></article>');
    $('#messages').scrollTo('max');

	var reply = $msg({to: from, from: to, type: 'chat'})
            .cnode(Strophe.copyElement(body));
    }

    // we must return true to keep the handler alive.
    // returning false would remove it after it finishes.
    return true;
}

function sendMessage() {
    connection.send();
}

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);
    connection.rawInput = rawInput;
    connection.rawOutput = rawOutput;

    $('#connexion').bind('click', function () {
	var button = this;
	if (button.innerHTML == 'connect') {
	    button.innerHTML = 'disconnect';

	    //connection.connect($('#jid').get(0).value,
		//	       $('#pass').get(0).value,
		//	       onConnect);
        connection.connect('sean@localhost', 'sean', onConnect)
	} else {
	    button.innerHTML = 'connect';
	    connection.disconnect();
	}
    });
    $('#inputSend').bind('click', sendMessage);
})


